package org.ko.core.websupport.springmvc;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.util.StringUtils;

/**
 * 日期编辑
 * 
 * 根据日期字符串长度判断是长日期还是短日期。只支持yyyy-MM-dd，yyyy-MM-dd HH:mm:ss两种格式�?
 * 
 */
public class DateTypeEditor extends PropertyEditorSupport {
	public static final DateFormat DF_ISO_LONG = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
	public static final DateFormat DF_LONG = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static final DateFormat DF_SHORT = new SimpleDateFormat("yyyy-MM-dd");
	//public static final Pattern P_ISO_LONG_WITH_T = Pattern.compile("^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[0-1]|0[1-9]|[1-2][0-9])T(2[0-3]|[0-1][0-9]):([0-5][0-9]):([0-5][0-9])(\\.[0-9]+)?(Z|[+-](?:2[0-3]|[0-1][0-9]):[0-5][0-9])?$");
	//public static final Pattern P_ISO_LONG = Pattern.compile("^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[0-1]|0[1-9]|[1-2][0-9]) (2[0-3]|[0-1][0-9]):([0-5][0-9]):([0-5][0-9])(\\.[0-9]+)?(Z|[+-](?:2[0-3]|[0-1][0-9]):[0-5][0-9])?$");
	//public static final Pattern P_ISO_SHORT = Pattern.compile("^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[0-1]|0[1-9]|[1-2][0-9])?$");
	
	/**
	 * 短类型日期长�?
	 */
	public static final int SHORT_DATE = 10;
	public static String getLongDate(Date src){
		return getDate(src,DF_LONG);
	}
	public static String getDate(Date src,DateFormat f){
		if(src==null)return "";
		else{
			return f.format(src);
		}
	}
	public static String getShortDate(Date src) {
		return getDate(src,DF_SHORT);
	}
	public void setAsText(String text) throws IllegalArgumentException {
		if (!StringUtils.hasText(text)) {
			setValue(null);
			return;
		}
		text = text.trim();
		if(text.contains("T")){
			try {
				setValue(DF_ISO_LONG.parse(text));
			} catch (ParseException ex) {
				IllegalArgumentException iae = new IllegalArgumentException(
						"Could not parse date: " + ex.getMessage());
				iae.initCause(ex);
				throw iae;
			}
		}else if(text.contains(":")){
			try {
				setValue(DF_LONG.parse(text));
			} catch (ParseException e) {
				setValue(null);
			}
		}
		else if(text.contains("-")){
			try {
				setValue(DF_SHORT.parse(text));
			} catch (ParseException e) {
				setValue(null);
			}
		}
		else{
			setValue(text);
		}
	}

	/**
	 * Format the Date as String, using the specified DateFormat.
	 */
	public String getAsText() {
		Date value = (Date) getValue();
		return (value != null ? DF_LONG.format(value) : "");
	}
	
	public static void main(String[] args) {
		//Matcher m = P_ISO_LONG_WITH_T.matcher("2013-03-13T25:00:00");
		//System.out.println(m.matches());
	}
	
}
